package com.qf.zyh.dao.admin.Impl;

import com.qf.zyh.dao.admin.AdminDao;
import com.qf.zyh.entity.User;
import com.qf.zyh.util.DBUtil;
import com.qf.zyh.util.StrUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AdminDaoImpl implements AdminDao {
    QueryRunner qr = new QueryRunner();
    @Override
    public User getadmin(String username) {
        try {
            return qr.query(DBUtil.getConnection(),"select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user where uname=?",new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<User> seleall() {
            try {
                return qr.query(DBUtil.getConnection(),"select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user",new BeanListHandler<>(User.class));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
    }
    @Override
    public List<User> selein(String username, String sex) throws SQLException {
        String sql = "select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user where 1 = 1";
        List<Object> args = new ArrayList<>();
        if (StrUtils.empty(username)) {
            sql=sql+" and uname like ?";
            args.add("%"+username+"%");
        }
        if (StrUtils.empty(sex)) {
            sql=sql+" and usex=?";
            args.add(sex);
        }
        return qr.query(DBUtil.getConnection(),sql,new BeanListHandler<>(User.class),args.toArray());
    }

    @Override
    public int deleUser(Integer uid) {
        try {
            return qr.update(DBUtil.getConnection(),"delete from user where uid=?",uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
